<?php

if_get('/upload_batches', function ()
{
    list(
        $inputs['number']
    ) = input_list(
        'number'
    );
    $inputs = array_filter($inputs, 'not_null');

    return render('upload_batch/list', [
        'upload_batches' => dao('upload_batch')->find_all_by_column($inputs),
    ]);
});

if_get('/upload_batches/add', function ()
{
    return render('upload_batch/add');
});

if_post('/upload_batches/add', function ()
{
    $file_info = input_file('file');

    $file_path = $file_info['tmp_name'];

    $file_md5 = md5_file($file_path);

    $excel = PHPExcel_IOFactory::load($file_path);

    $upload_batch = dao('upload_batch')->find_by_number($file_md5);

    if ($upload_batch->is_null()) {

        $upload_batch = upload_batch::create();

        $upload_batch->number = $file_md5;

    } else {

        $upload_batch->number = $file_md5;

        $upload_batch->delete_relation_entities();
    }

    otherwise($excel->getSheetCount() === 1, '上传的表格中有太多 sheet');

    $excel->setActiveSheetIndex(0); // 选中第一个 sheet

    $active_sheet = $excel->getActiveSheet();

    $row_count = $active_sheet->getHighestRow();
    $col_count = $active_sheet->getHighestColumn();

    $keys = [];

    for ($col = 'A'; $col <= $col_count; $col ++) {

        $keys[$col] = $active_sheet->getCell($col.'1')->getValue();
    }

    for ($row = 2; $row < $row_count; $row++) {

        $data_info = [];

        for ($col = 'A'; $col <= $col_count; $col ++) {

            $data_info[$keys[$col]] = $active_sheet->getCell($col.$row)->getValue();
        }

        otherwise(
            isset($data_info['序号'])
            && isset($data_info['收货人'])
            && isset($data_info['收货人手机'])
            && isset($data_info['小区名'])
            && isset($data_info['门牌号'])
            , '表头不完整，请参考导入模版');

        otherwise(
            $data_info['序号']
            && $data_info['收货人']
            && $data_info['收货人手机']
            && $data_info['小区名']
            && $data_info['门牌号']
            , '第'.$row.'行数据不完整');

        $raw_address = raw_address::create();
        $raw_address->number = $data_info['序号'];
        $raw_address->person_name = $data_info['收货人'];
        $raw_address->person_mobile_number = $data_info['收货人手机'];
        $raw_address->estate_name = $data_info['小区名'];
        $raw_address->house_address = $data_info['门牌号'];
        $raw_address->set_status_init();
        $raw_address->upload_batch = $upload_batch;

        format_address($raw_address);
    }

    $upload_batch->format_time = datetime();

    return redirect('/upload_batches/detail/'.$upload_batch->id);
});

if_get('/upload_batches/detail/*', function ($upload_batch_id)
{
    $upload_batch = dao('upload_batch')->find($upload_batch_id);
    otherwise($upload_batch->is_not_null(), 'upload_batch not found');

    return render('upload_batch/detail', [
        'upload_batch' => $upload_batch,
        'raw_addresses' => $upload_batch->raw_addresses,
    ]);
});

if_post('/upload_batches/detail/*', function ($upload_batch_id)
{
    $upload_batch = dao('upload_batch')->find($upload_batch_id);
    otherwise($upload_batch->is_not_null(), 'upload_batch not found');

    foreach ($upload_batch->raw_addresses as $raw_address) {

        format_address($raw_address);
    }

    $upload_batch->format_time = datetime();

    return redirect('/upload_batches/detail/'.$upload_batch->id);
});

if_post('/upload_batches/export/*', function ($upload_batch_id)
{
    $upload_batch = dao('upload_batch')->find($upload_batch_id);
    otherwise($upload_batch->is_not_null(), 'upload_batch not found');

    $excel = new PHPExcel();

    $excel->getProperties()->setCreator("Delivery Address Format System")
        ->setLastModifiedBy("Delivery Address Format System")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Export from delivery address format system for upload batch number ".$upload_batch->number)
        ->setKeywords("Addresses ".$upload_batch->number)
        ->setCategory("Addresses");

    $excel->setActiveSheetIndex(0)
        ->setCellValue('A1', '唯一编号')
        ->setCellValue('B1', '小区')
        ->setCellValue('C1', '楼栋')
        ->setCellValue('D1', '层')
        ->setCellValue('E1', '门牌号')
        ->setCellValue('F1', '收货人')
        ->setCellValue('G1', '联系方式');

    $index = 1;

    foreach ($upload_batch->raw_addresses as $raw_address) {

        $index += 1;

        $formated_address = $raw_address->snap_formated_address_string;

        $estate = dao('estate')->find_by_name($raw_address->estate_name);
        otherwise($estate->is_not_null(), sprintf('第 %s 条地址记录 [%s] 的小区没有配置', $raw_address->number, $formated_address));

        $output_address_slot = $estate->output_address_slot;
        otherwise($output_address_slot->is_not_null(), sprintf('第 %s 条地址记录 [%s] 的小区没有配置输出格式地址槽', $raw_address->number, $formated_address));

        list($matched, $match_infos) = $estate->output_address_slot->match_address($formated_address);
        otherwise($matched, sprintf('第 %s 条地址记录 [%s] 格式化有问题', $raw_address->number, $formated_address));

        $address_part_1 = $address_part_2 = $address_part_3 = '';

        foreach ($match_infos as $info) {

            if (
                $info['unit'] == '层'
            ) {
                $address_part_2 = $info['value'];
                continue;
            }

            if (
                $info['unit'] == '室'
                || $info['unit'] == '间'
                || $info['unit'] == '屋'
                || $info['unit'] == '房'
                || $info['unit'] == '号'
                || $info['unit'] == '门'
            ) {
                $address_part_3 = $info['value'];
                continue;
            }

            $address_part_1 .= $info['string'];
        }

        if (! $address_part_2) {

            $address_part_2_tmp = substr($address_part_3, 0, -2);

            if ($address_part_2_tmp) {

                $address_part_2 = $address_part_2_tmp;
            }
        }

        $excel->setActiveSheetIndex(0)
            ->setCellValue('A'.$index, 'j'.datetime('now', 'YmdHis').$index)
            ->setCellValue('B'.$index, $estate->name)
            ->setCellValue('C'.$index, $address_part_1)
            ->setCellValue('D'.$index, $address_part_2)
            ->setCellValue('E'.$index, $address_part_3)
            ->setCellValue('F'.$index, $raw_address->person_name)
            ->setCellValue('G'.$index, $raw_address->person_mobile_number);
    }

    $excel->getActiveSheet()->setTitle('addresses');

    $excel->setActiveSheetIndex(0);

    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="formated_address_'.$upload_batch->number.'-'.datetime('now', 'YmdHis').'.xlsx"');
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');

    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT');
    header ('Cache-Control: cache, must-revalidate');
    header ('Pragma: public');

    $writer = PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
    $writer->save('php://output');
    exit;
});

if_post('/upload_batches/delete/*', function ($upload_batch_id)
{
    $upload_batch = dao('upload_batch')->find($upload_batch_id);
    otherwise($upload_batch->is_not_null(), 'upload_batch not found');

    $upload_batch->delete_relation_entities();
    $upload_batch->delete();

    return redirect('/upload_batches');
});
